package org.swimv2.servlets;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.swimv2.entities.Job;
import org.swimv2.entities.User;
import org.swimv2.interfaces.JobsManagerRemote;
import org.swimv2.interfaces.SearchManagerRemote;
import org.swimv2.utils.ContextUtil;

/**
 * Servlet implementation class EvalJobReq
 */
public class EvalJobReqServlet extends HttpServlet {
	private static final long serialVersionUID = -3981732491930178913L;

	private User curr_u;

	private JobsManagerRemote   mgr_j = null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EvalJobReqServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		try {
			Context ctx = ContextUtil.getInitialContext();
			mgr_j = (JobsManagerRemote)   ctx.lookup("JobsManagerJNDI");
			
			RequestDispatcher disp;
			disp = request.getRequestDispatcher("user/profile.jsp");
			
			// L'utente loggato
			curr_u = (User) request.getSession().getAttribute("user");
			
			/* L'utente deve essere loggato */
			if (curr_u == null) {
				request.setAttribute("error_message", "Errore: nessun utente selezionato");
				disp.forward(request, response);
				return;
			}
			
			// La richiesta di aiuto lavorativo
			Job j = mgr_j.getJob( Integer.parseInt(request.getParameter("req_id")) );

			/* Controllo parametri */
			if (j == null ||
			    curr_u.getId() == j.getClient().getId() ||
			    curr_u.getId() != j.getWorker().getId())
			{
				request.setAttribute("message_error", "Errore nella gestione della richiesta di amicizia.");
			}
			
			/* Valuta una richiesta di aiuto lavorativo */
			else {
				String param_how = request.getParameter("how");
				
				/* Accetta richiesta di aiuto lavorativo */
				if (param_how.equals("accept")) {
					mgr_j.openJob(j);
				}
				/* Rifiuta richiesta di aiuto lavorativo */
				else if (param_how.equals("reject")) {
					mgr_j.removeJob(j);
				}
				
				request.setAttribute("message", "Valutazione richiesta effettuata.");
			}
			disp.forward(request, response);
		}
		catch (NamingException e) {
			e.printStackTrace();
		}	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
